﻿using CommonDevelop;
using CommonEngine;
using ManageService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using WebAdmin.Handler;

namespace WebAdmin.Controllers
{
    /// <summary>
    /// 附件
    /// </summary>
    public class AnnexesController : BaseController
    {
        private readonly IEncService _EncService;
        private readonly IPicService _PicService;
        private readonly IPathProvider pathProvider;
        /// <summary>
        /// 构造注入
        /// </summary>
        public AnnexesController(IEncService EncService, IPicService PicService, IPathProvider pathProvider)
        {
            this._EncService = EncService;
            this._PicService = PicService;
            this.pathProvider = pathProvider;
        }

        #region 视图功能

        /// <summary>
        /// 上传列表页面
        /// </summary>
        [HttpGet]
        public ActionResult UploadForm()
        {
            return View();
        }
        /// <summary>
        /// 下载列表页面
        /// </summary>
        [HttpGet]
        public ActionResult DownForm()
        {
            return View();
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 上传附件分片数据
        /// </summary>
        /// <param name="fileGuid">文件主键</param>
        /// <param name="chunk">分片序号</param>
        /// <param name="Filedata">文件数据</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [DisableRequestSizeLimit]
        public ActionResult UploadAnnexesFileChunk(string fileGuid, int chunk, int chunks, IFormFile Filedata)
        {
            //没有文件上传，直接返回
            if (Filedata == null || string.IsNullOrEmpty(Filedata.FileName) || Filedata.Length == 0)
            {
                if (Request.Form.Files.Count > 0)
                {
                    Filedata = Request.Form.Files[0];
                }
                else
                {
                    return NotFound();
                }
            }
            this._EncService.SaveChunkAnnexes(fileGuid, chunk, Filedata.OpenReadStream());
            return Success("保存成功");
        }

        /// <summary>
        /// 移除附件分片数据
        /// </summary>
        /// <param name="fileGuid">文件主键</param>
        /// <param name="chunks">总分片数</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [DisableRequestSizeLimit]
        public ActionResult RemoveAnnexesFileChunk(string fileGuid, int chunks)
        {
            this._EncService.RemoveChunkAnnexes(fileGuid, chunks);
            return Success("移除成功");
        }

        /// <summary>
        /// 合并上传附件的分片数据
        /// </summary>
        /// <param name="folderId">附件夹主键</param>
        /// <param name="fileGuid">文件主键</param>
        /// <param name="fileName">文件名</param>
        /// <param name="chunks">文件总分片数</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [DisableRequestSizeLimit]
        public ActionResult MergeAnnexesFile(string folderId, string fileGuid, string fileName, int chunks)
        {
            string RelativePath = this.pathProvider.MapPath("Enc");
            string res = this._EncService.SaveAnnexes(folderId, fileGuid, fileName, RelativePath, chunks);
            if (!string.IsNullOrEmpty(res))
            {
                return Success(res);
            }
            else
            {
                return Fail("保存文件失败");
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteAnnexesFile(string EncId)
        {
            var data = this._EncService.GetEnc(EncId);
            if (data != null)
            {
                this._EncService.RemoveEnc(data.EncId);
                //删除文件
                if (System.IO.File.Exists(data.EncAddress))
                    System.IO.File.Delete(data.EncAddress);
            }
            return Success("删除附件成功");
        }

        #endregion

        #region 获取数据

        /// <summary>
        /// 下载文件
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public void DownAnnexesFile(string EncId)
        {
            var data = this._EncService.GetEnc(EncId);
            if (data != null)
                this.DownloadBigFile(data.EncName, data.EncAddress);
        }

        /// <summary>
        /// 获取附件列表
        /// </summary>
        [HttpGet]
        public ActionResult GetAnnexesFileList(string EncObjectId)
        {
            var data = this._EncService.GetEncList(EncObjectId);
            return Success("响应成功", data);
        }

        /// <summary>
        /// 获取附件夹信息
        /// </summary>
        [HttpGet]
        public ActionResult GetFileNames(string id)
        {
            string info = "File:{0},Size:{1}";
            int count = 0;
            decimal length = 0;
            var data = this._EncService.GetEncList(id);
            if (data != null)
            {
                count = data.Count;
                length = data.Sum(a =>
                {
                    int i = 0;
                    int.TryParse(a.FileSize, out i);
                    return i;
                });
            }
            info = string.Format(info, count, this.FormatSize(length));
            return Success(info);
        }
        private string FormatSize(decimal size)
        {
            if (size <= 0)
                return "0";
            else if (size < 1024.00M)
                return Math.Round(size, 2).ToString() + " 字节";
            else if (size >= 1024.00M && size < 1048576M)
                return Math.Round((size / 1024.00M), 2).ToString() + " KB";
            else if (size >= 1048576M && size < 1073741824M)
                return Math.Round((size / 1024.00M / 1024.00M), 2).ToString() + " MB";
            else if (size >= 1073741824M)
                return Math.Round((size / 1024.00M / 1024.00M / 1024.00M), 2).ToString() + " GB";
            else
                return string.Empty;
        }

        #endregion

        #region---图片管理---

        [HttpGet]
        public ActionResult ShowPic(string id)
        {
            string PicGroup_No = string.IsNullOrEmpty(id) ? "" : id;
            var DLs = this._PicService.ShowPic(PicGroup_No);
            ViewBag.PicGroup_No = PicGroup_No;
            if (DLs.Any())
            {
                string result = "";
                foreach (var v in DLs)
                    result += $"\"{v.PicUrl}\"" + ",";

                result = result.Substring(0, result.Length - 1);
                ViewBag.Picture = result;
            }
            else
                ViewBag.Picture = "";

            return View();
        }

        [HttpGet]
        public ActionResult ShowOnlyPic(string id)
        {
            string PicGroup_No = string.IsNullOrEmpty(id) ? "" : id;
            var DLs = this._PicService.ShowPic(PicGroup_No);
            ViewBag.PicGroup_No = PicGroup_No;
            if (DLs.Any())
            {
                string result = "";
                foreach (var v in DLs)
                    result += $"\"{v.PicUrl}\"" + ",";

                result = result.Substring(0, result.Length - 1);
                ViewBag.Picture = result;
            }
            else
                ViewBag.Picture = "";

            return View();
        }

        [HttpPost]
        public ActionResult PicDelet(string Arr)
        {
            var FileArr = _PicService.DeletePicEx(Arr);
            if (!FileArr.IsEmpty())
            {
                CommonOP.DeleteFile(FileArr);
                return Json(new { resultCode = 1, resultMsg = "OK" });
            }
            else
                return Json(new { resultCode = 0, resultMsg = "No" });
        }

        #endregion
    }
}
